package com.bmps.springcloud.insuredmicroservice.service.underwrite.strategy.riskamount;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description:
 * 风险保额策略加载
 *
 * @author jackdaw
 * @date 2020-04-16 10:49
 */
@Component
@Slf4j
public class InsuranceRiskStrategyFactory {
    private final static ConcurrentHashMap<String, InsuranceRiskAmountStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();

    public InsuranceRiskStrategyFactory(Map<String, InsuranceRiskAmountStrategy> riskStrategyMap) {

        STRATEGY_MAP.clear();
        try {
            Resource resource = new ClassPathResource("insuranceriskamountstrategy.properties");
            InputStream inputStream = resource.getInputStream();
            Properties properties = new Properties();
            properties.load(inputStream);
            for (String key : properties.stringPropertyNames()) {
                InsuranceRiskAmountStrategy strategy = riskStrategyMap.get(properties.getProperty(key));
                Arrays.stream(key.split(",")).forEach(s -> {
                    STRATEGY_MAP.put(s, strategy);
                    log.info("insuranceriskamountstrategy add key: " + s + ", new instance:" + strategy);
                });
            }
        } catch (Exception e) {
            log.error("风险保额计算策略加载异常", e);
        }
    }

    public static InsuranceRiskAmountStrategy getStrategy(String key) {
        return STRATEGY_MAP.get(key);
    }
}
